# -*- coding: UTF-8 -*-
import scrapy
from scrapy.selector import Selector

from scrapy.http import Request
import traceback
from scrapy import signals
import os, sys
from pangolin.common.date_common import DateCommon
from pangolin.spider_enum.companyCodeEnum import getCompanyCode
from pangolin.common.db_operateCommon import *
from pangolin.common.string_common import StringCommon
from pangolin.items import TicketDetailItem
from pangolin.common.http_common import *
import logging
import re
from urlparse import urljoin
from pangolin.settings import IS_SAVE_SERVER
from pangolin.settings import IS_SNAPSHOT
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from PIL import Image
from datetime import *
import time
import urllib

reload(sys)
sys.setdefaultencoding('UTF-8')


class PangolinSpider(scrapy.Spider):
    name = 'tc_ticket_by_tc_scenery_m_spider'
    allowed_domain = 'ly.com'  # 允许爬虫运行的域

    def __init__(self, crawler, spider_name, city_code, company_code, task_id, task_date, timer_param,
                 timer_granularity, timer_id, url, lv_product_id, miss_product_flag):
        # 接受入参,全局引用
        self.save_server = IS_SAVE_SERVER
        self.snapshot = IS_SNAPSHOT

        self.spider_name = spider_name
        self.city_code = city_code
        self.company_code = company_code
        self.task_id = task_id
        self.task_date = task_date
        self.timer_param = timer_param
        self.timer_granularity = timer_granularity
        self.timer_id = timer_id
        self.url = url
        self.lv_product_id = lv_product_id
        self.miss_product_flag = miss_product_flag

        # 根据cityCode获得城市名称，并且设置起始页以及下一页
        db_operate = DbOperateClass()
        sql = "SELECT tc_name, city_name, product_id FROM cpa_care_product WHERE city_code = '" + city_code + "' AND business_code='TICKET'"
        logging.info("SELECT_SQL:%s" % sql)
        (fc, count) = db_operate.select_by_sql(sql)
        first_page_url = []
        lv_product_ids = {}
        for row in fc:
            if row[0] is not None:
                scenery_name = row[0]
                city_name = row[1]
                product_id = row[2]
                base_url = "http://m.ly.com/scenery/json/scenerynearycitylist.html?CountryId=0&ProvinceId=0&CityId=0&LbTypes=&keyword=sceneryName cityName"
                scenery_url = base_url.replace("sceneryName", scenery_name).replace("cityName", city_name)
                keyword = scenery_name + " " + city_name
                lv_product_ids.setdefault(base_url.replace("sceneryName cityName", urllib.quote(str(keyword), '()')),
                                          product_id)
                first_page_url.append(scenery_url)
        self.lv_product_ids = lv_product_ids
        self.start_urls = first_page_url

        self.base_urls = "http://m.ly.com"
        # 爬虫爬取前先删除同一批次同一城市的数据
        db_operate.delete_pd_and_cd_data("ticket_pdetail_tc", "ticket_cdetail_tc", getCompanyCode(company_code),
                                         city_code, task_id, task_date)
        # 绑定爬虫开始和结束信号，便于监听爬虫开始与结束
        self.crawler = crawler
        cs = crawler.signals
        cs.connect(self.spider_closed, signals.spider_closed)
        cs.connect(self.spider_opened, signals.spider_opened)

    def parse(self, response):
        try:
            dr = re.compile(r'<[^>]+>', re.S)
            json_data = dr.sub('', response.body)
            if json_data.find("{") > -1:
                sites = json.loads(json_data)
                total_count = sites['totalCount']
                if int(total_count) > 0:
                    product_tag = sites['sceneryinfo'][0]
                    relative_url = product_tag['href']
                    lowest_price = product_tag['adviceAmount']
                    star_level = product_tag['grade']
                    detail_url = urljoin(self.base_urls, relative_url)
                    lv_product_id = self.lv_product_ids.get(response.url)
                    request = Request(detail_url, meta={'lowest_price': lowest_price, 'lv_product_id': lv_product_id,
                                                        'star_level': star_level},
                                      callback=self.parse_product_list)
                    yield request
            else:
                pass
        except Exception as e:
            db_operate = DbOperateClass()
            logging.error("记录日志：标签变动 %s ,%s" % (response.url, e))
            logging.info("页面源码：%s ,%s" % (response.url, e))
            logging.error("tc_ticket_by_tc_scenery_m_spider_Exception: %s" % traceback.format_exc().replace("\"", "'"))

            # 错误描述只截取前500个字符，剩下的用***代替
            error_desc = traceback.format_exc().replace("\"", "'").replace(" ", "")
            if len(error_desc) > 500:
                error_desc = error_desc[:500] + '***'
            # 错误日志记入日志表
            sql = "insert into cpa_oper_log (log_type,company_code,busi_type,url,batch_num,timer_code,error_code,error_desc,task_id,task_date) values (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\" ,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" \
                  % ("C", getCompanyCode(self.company_code), "门票", response.url, self.task_date, "timer_code",
                     "error_code", error_desc, str(self.task_id), str(self.task_date))
            db_operate.update_by_sql(sql)
            if self.save_server == 'TRUE':
                http_common = HttpCommon()
                operate_log = {'type': 'LOG',
                               'log_type': "C",
                               'company_code': getCompanyCode(self.company_code),
                               'busi_type': "门票",
                               'url': response.url,
                               'batch_num': self.task_date,
                               'timer_code': "timer_code",
                               'error_code': "error_code",
                               'error_desc': error_desc,
                               'task_id': str(self.task_id),
                               'task_date': str(self.task_date)}
                # http_common.get_method(operate_log)

    def parse_product_list(self, response):  # 页面解析函数，这里必须为parse()
        lowest_price = response.meta['lowest_price']
        lv_product_id = response.meta['lv_product_id']
        star_level = response.meta['star_level']
        sels = Selector(response)
        try:
            item = TicketDetailItem()
            item['type'] = "TICKET"
            item['timer_param'] = self.timer_param
            item['timer_granularity'] = self.timer_granularity
            item['business_type'] = "ticket"

            item['product_table'] = "ticket_pdetail_tc"
            item['data_type'] = "TicketDetail"
            item['detail_id'] = DateCommon.get_id_by_datetime()
            item['company_code'] = getCompanyCode(self.company_code)
            item['platform_code'] = "WAP"  # 操作平台WAP，PC
            item['city_code'] = self.city_code
            item['scenery_name'] = StringCommon.remove_blank(
                sels.xpath('//*[@class="pic_mask"]/h3/text()').extract()[0])  # 景点名称
            item['scenery_addr'] = StringCommon.remove_blank(
                sels.xpath('//*[@class="a_address tcTraObj"]/text()').extract()[0])  # 景点地址
            item['detail_url'] = response.url  # 详情页链接
            item['product_id'] = item['detail_url'].split('scenerydetail_')[1].split('_')[0]

            # 产品详情
            item['lowest_price'] = lowest_price
            item['score'] = sels.xpath('//*[@class="pic_mask"]/p/text()').extract()[0]  # 评分
            item['image_num'] = ""
            item['introduction'] = sels.xpath('//*[@class="notices"]/div[2]/p/text()').extract()[0]
            item['score_tag'] = ""
            if star_level.count("A") > 0:
                item['star_level'] = str(star_level.count("A")) + "A"
            else:
                item['star_level'] = ""
            item['create_time'] = DateCommon.get_current_date()
            item['update_time'] = item['create_time']
            item['task_id'] = self.task_id
            item['task_date'] = self.task_date
            item['lv_product_id'] = lv_product_id
            if self.snapshot == 'TRUE':
                # 获得截图地址
                compress_path = self.save_screenshot(response, item['product_id'], self.city_code,
                                                     self.company_code, self.task_id, self.task_date)
                item['snapshot_addr'] = compress_path
            else:
                item['snapshot_addr'] = " "
            # 商品详情
            item['commodity_table'] = "ticket_cdetail_tc"
            item['commodity_type'] = []  # 商品类型或名称
            item['commodity_id'] = []  # 商品id
            item['commodity_name'] = []  # 商品名称
            item['commodity_url'] = []  # 商品名称
            item['sale_cond'] = []  # 提前时间、销售条件
            item['refund_cond'] = []  # 退改条件
            item['rack_rate'] = []  # 门市价
            item['sale_price'] = []  # 售价
            item['preferential'] = []  # 优惠
            item['price_list_id'] = ""
            product_tag = sels.css('.ajax_tickets')
            if product_tag:
                sites_evens = sels.css('.ajax_tickets .ticket')
                for i, sites in enumerate(sites_evens):
                    commodity_type = sites.css('.dd_icon').xpath('text()').extract()[0]
                    child_site = sites.css('.ticket dd')
                    for child_sites in child_site:
                        commodity_name = StringCommon.remove_blank(
                            child_sites.css('.h4').xpath('text()').extract()[0])
                        commodity_url_tag = child_sites.css('.btn.btn-top.line_btn').xpath('@href').extract()
                        if commodity_url_tag:
                            commodity_url = urljoin(self.base_urls, commodity_url_tag[0])
                        commodity_id = child_sites.css('dd').xpath('@ticketid').extract()[0]
                        sale_cond = ""
                        refund_cond = ""
                        rack_rate = child_sites.css('.price').xpath('@ticketid').extract()[0]
                        sale_price = StringCommon.remove_blank(
                            child_sites.css('.tc-price').xpath('text()').extract()[0])
                        preferential = ""

                        item['commodity_type'].append(commodity_type)  # 商品类型或名称
                        item['commodity_id'].append(commodity_id)  # 商品id
                        item['commodity_name'].append(commodity_name)  # 商品名称
                        item['commodity_url'].append(commodity_url)  # 商品链接
                        item['sale_cond'].append(sale_cond)  # 提前时间、销售条件
                        item['refund_cond'].append(refund_cond)  # 退改条件
                        item['rack_rate'].append(rack_rate)  # 门市价
                        item['sale_price'].append(sale_price)  # 售价
                        item['preferential'].append(preferential)  # 优惠
                yield item
            else:
                detail_url = "http://m.ly.com/scenery/json/SceneryPriceFrame.html?sceneryId={}&_=1494406900188".format(
                    item['product_id'])
                request = Request(detail_url, meta={'item': item}, callback=self.parse_commodity_list)
                yield request

        except Exception as e:
            db_operate = DbOperateClass()
            logging.info("记录日志：标签变动 %s ,%s" % (response.url, e))
            logging.info("页面源码：%s ,%s" % (response.url, response.body))
            logging.error("qnr_ticket_by_scenery_m_spider_Exception: %s" % traceback.format_exc().replace("\"", "'"))
            # 错误描述只截取前500个字符，剩下的用***代替
            error_desc = traceback.format_exc().replace("\"", "'").replace(" ", "")
            if len(error_desc) > 500:
                error_desc = error_desc[:500] + '***'
            # 错误日志记入日志表
            sql = "insert into cpa_oper_log (log_type,company_code,busi_type,url,batch_num,timer_code,error_code,error_desc,task_id,task_date) values (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\" ,\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")" \
                  % ("C", getCompanyCode(self.company_code), "门票", response.url, self.task_date, "timer_code",
                     "error_code", error_desc, str(self.task_id), str(self.task_date))
            db_operate.update_by_sql(sql)
            if self.save_server == 'TRUE':
                http_common = HttpCommon()
                operate_log = {'type': 'LOG',
                               'log_type': "C",
                               'company_code': getCompanyCode(self.company_code),
                               'busi_type': "门票",
                               'url': response.url,
                               'batch_num': self.task_date,
                               'timer_code': "timer_code",
                               'error_code': "error_code",
                               'error_desc': error_desc,
                               'task_id': str(self.task_id),
                               'task_date': str(self.task_date)}
                # http_common.get_method(operate_log)

    def parse_commodity_list(self, response):
        item = response.meta['item']
        dr = re.compile(r'<[^>]+>', re.S)
        json_data = dr.sub('', response.body)
        if json_data.find("{") > -1:
            sites = json.loads(json_data)
            item['scenery_name'] = sites['SceneryPrices'][0]['DestinationName']
            commodity_data = sites['SceneryPrices'][0]['ChannelPriceModelEntityList']
            if commodity_data is not None:
                for site in commodity_data:
                    commodity_type = site['ConsumersTypeName']
                    channel_price_list = site['ChannelPriceEntityList']
                    for channel_price in channel_price_list:
                        commodity_name = channel_price['TicketName']
                        # commodity_url = channel_price['OrderUrl']
                        # if commodity_url.find("ticketId") != -1:
                        #     commodity_url = "http://www.ly.com/" + channel_price['OrderUrl']
                        #     match = re.search(r'ticketId=\d+', commodity_url)
                        #     commodity_id = match.group(0).split('ticketId=')[1]
                        # elif commodity_url.find("zizhuyou") != -1:
                        #     commodity_url = "http://zby.ly.com" + channel_price['OrderUrl']
                        #     commodity_id = commodity_url.split('/')[5].split('-')[0]
                        # elif commodity_url.find("ProductDetail") != -1:
                        #     commodity_url = "http://www.ly.com/" + channel_price['OrderUrl']
                        #     commodity_id = commodity_url.split('ProductDetail_')[1].split('.html')[0]
                        # else:
                        #     commodity_id = ""
                        commodity_url = ""
                        commodity_id = channel_price['TicketTypeId']
                        sale_cond = channel_price['orderTimeContent']
                        refund_cond = channel_price['RefundModifyRule']
                        rack_rate = channel_price['Amount']
                        sale_price = channel_price['AmountAdvice']
                        preferential = ""
                        preferential_list = channel_price['TicketTagEntityList']
                        if preferential_list is not None:
                            for preferential_json in preferential_list:
                                preferential_id = preferential_json['Id']
                                if str(preferential_id) == '2100602':
                                    preferential = preferential_json['Description']
                        item['commodity_type'].append(commodity_type)  # 商品类型或名称
                        item['commodity_id'].append(commodity_id)  # 商品id
                        item['commodity_name'].append(commodity_name)  # 商品名称
                        item['commodity_url'].append(commodity_url)  # 商品链接
                        item['sale_cond'].append(sale_cond)  # 提前时间、销售条件
                        item['refund_cond'].append(refund_cond)  # 退改条件
                        item['rack_rate'].append(rack_rate)  # 门市价
                        item['sale_price'].append(sale_price)  # 售价
                        item['preferential'].append(preferential)  # 优惠
        return item

    # 按元素截图
    def save_screenshot(self, response, productId, cityCode, companyCode, taskId, taskDate):
        compress_path = ""
        try:
            fileName = getCompanyCode(
                companyCode) + "__" + cityCode + "__" + taskId + "__" + taskDate + "__" + productId + ".png"
            service_args = [
                '--proxy=' + response.meta['proxy'],
                '--load-images=no', ]
            dcap = dict(DesiredCapabilities.PHANTOMJS)
            # # 伪造ua信息
            # dcap["phantomjs.page.settings.userAgent"] = (request.headers['User-Agent'])
            dcap["phantomjs.page.settings.resourceTimeout"] = 5000  # 超时
            # 添加头文件
            dcap["phantomjs.page.customHeaders.Referer"] = response.url
            driver = webdriver.PhantomJS(desired_capabilities=dcap, service_args=service_args)  # 线上使用方式
            logging.info("%s PhantomJS is getUrl..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            driver.set_page_load_timeout(100)
            driver.set_script_timeout(100)
            driver.get(response.url)
            # print driver.page_source
            # 截图
            path = os.getcwd() + "/screenshot/" + fileName
            logging.info("%s save_screenshot is starting..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            driver.save_screenshot(path)
            logging.info("%s save_screenshot is end..." % datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            # 根据元素获得裁剪区域的坐标
            element = driver.find_element_by_xpath("//*[@id='mainPage']/div[1]")
            element1 = driver.find_element_by_xpath("//*[@id='mainPage']/div[2]/div[2]")
            left = int(element.location['x'])
            top = int(element.location['y'])
            right = int(element.location['x'] + element.size['width'])
            bottom = int(50 + element.location['y'] + element.size['height'] + element1.size['height'])
            # 根据获得的裁剪区域坐标截图
            compress_path = os.getcwd() + "/compressImage/" + fileName
            im = Image.open(path)
            im = im.crop((left, top, right, bottom))  # (left, top, right, bottom)
            im.save(compress_path)
            os.remove(path)
        except Exception as e:
            logging.error("截图失败 %s ,%s" % (response.url, e))
        finally:
            try:
                driver.quit()
            except Exception as e:
                logging.error("driver.quit_failed %s" % e)
        return compress_path

    @classmethod
    def from_crawler(cls, crawler, **kwargs):
        logging.info('inside_from_crawler: ')
        if kwargs['miss_product_flag'] == 'FALSE':
            kwargs['url'] = ''
            kwargs['lv_product_id'] = ''
        else:
            kwargs['timer_granularity'] = ''
            kwargs['timer_id'] = ''

        return cls(
            crawler,
            spider_name=kwargs['spider_name'],
            city_code=kwargs['city_code'],
            company_code=kwargs['company_code'],
            task_id=kwargs['task_id'],
            task_date=kwargs['task_date'],
            timer_param=kwargs['timer_param'],
            timer_granularity=kwargs['timer_granularity'],
            timer_id=kwargs['timer_id'],
            url=kwargs['url'],
            lv_product_id=kwargs['lv_product_id'],
            miss_product_flag=kwargs['miss_product_flag']
        )

    def spider_opened(self, spider):
        logging.info('Spider_opened_list: %s' % spider.name)
        # 爬虫设为启动状态2
        db_operate = DbOperateClass()
        db_operate.update_status(2, "PYTHON", self.timer_id)

    def spider_closed(self, spider, reason):
        logging.info('spider_closed_list: %s ,reason:%s' % (spider.name, reason))
        if self.save_server == 'TRUE':
            time.sleep(2)
            http_common = HttpCommon()
            payload = {'type': 'TASK',
                       'company_code': getCompanyCode(self.company_code),
                       'business_type': 'TICKET',
                       'task_id': self.task_id,
                       'timer_param': self.timer_param,
                       'timer_granularity': self.timer_granularity,
                       'city_code': self.city_code}
            # http_common.get_method(payload)
        db_operate = DbOperateClass()
        sql = "SELECT timer.timer_status FROM cpa_timer timer WHERE timer.timer_type='PYTHON' AND timer.timer_id = '" \
              + self.timer_id + "'"
        (fc, count) = db_operate.select_by_sql(sql)
        spider.logger.info('SELECT_COUNT: %s ,SQL:%s' % (count, sql))
        timer_status = ""
        for row in fc:
            timer_status = row[0]
        logging.info("timer_status:%s" % timer_status)
        if timer_status == '2':
            db_operate.update_status(5, "PYTHON", self.timer_id)
